package io.renren.midplat.offerslook.task;
import java.util.Date;

import com.alibaba.fastjson.JSON;
import io.renren.common.exception.RRException;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.HttpUtils;
import io.renren.midplat.fuseclick.task.BatchSetOffers;
import io.renren.midplat.offerslook.model.GetOfferModel;
import io.renren.midplat.offerslook.model.ResultModel;
import io.renren.modules.offer.entity.OfferEntity;
import io.renren.modules.offer.service.OfferService;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * batchGetOffersByOfferslook为spring bean的名称
 *
 * @Description /aff/v1/batches/offers
 * @Author haijun.zhang@luckincoffee.com
 * @Date 2018-08-07 9:45
 */
@Component("batchGetOffersByOfferslook")
public class BatchGetOffers {

    @Autowired
    private OfferService offerService;
    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(BatchGetOffers.class);
    @Value("${offerslook.apiDomain}")
    private String apiDomain;
    @Value("${offerslook.getBatchesOffersURI}")
    private String getBatchesOffersURI;
    @Value("${offerslook.userName}")
    private String userName;
    @Value("${offerslook.password}")
    private String password;

    public static final int limit = 30;

    public static final String urlParams=  "?type=personal&contains=description&filters[status][EQUAL_TO]=active";

    private UsernamePasswordCredentials usernamePasswordCredentials;

    private String batchNo;

    @Autowired
    @Qualifier("batchSetOffersByfuseclick")
    private BatchSetOffers batchSetOffers;

    public void taskRun() {

        batchNo = DateUtils.get14date();
        LOGGER.info("Offerslook拉取数据批处理开始 start");
        usernamePasswordCredentials= new UsernamePasswordCredentials(userName, password);

        ResultModel resultModel = new ResultModel();

        try {

            LOGGER.info("批次号:"+batchNo);
            int requestNum = getRquestCount();
            //线程沉睡2秒，访问太快了，人家会连接超时~~~~
            Thread.sleep(2000);
            LOGGER.info("request count:" + requestNum);
            LOGGER.info("request for start:");
            List<GetOfferModel.OfferAllBean> offerAllBeanList = new ArrayList<GetOfferModel.OfferAllBean>();

            for (int i = 1;i<=requestNum;i++){
                LOGGER.info("request for start:"+i);
                Map<String, String> params = new LinkedHashMap<>();
                params.put("offset", i+"");
                params.put("limit", limit+"");
                String response = HttpUtils.doGet(apiDomain+getBatchesOffersURI+urlParams,params,usernamePasswordCredentials);
                LOGGER.info("response:{}",response);

                resultModel = JSON.parseObject(response, ResultModel.class);

                if (resultModel.getCode() == 0) {
                    GetOfferModel getOfferModel = JSON.parseObject(resultModel.getData(), GetOfferModel.class);
                    offerAllBeanList.addAll(getOfferModel.getOfferAll()) ;
                } else {
                    throw new RRException("请求异常");
                }
                Thread.sleep(2000);
            }
            LOGGER.info("request for end:");
            LOGGER.debug("offerAllBeanList.size:{}",offerAllBeanList.size());

            List<OfferEntity> offerEntityList = new ArrayList<OfferEntity>();
            transfer(offerAllBeanList,offerEntityList);
            LOGGER.debug("offerEntityList.size:{}",offerEntityList.size());
            if(offerAllBeanList.size()!=offerEntityList.size()){
                throw new RRException("数据不一致，offerAllBeanList.size:" + offerAllBeanList.size() +"offerEntityList.size:"+offerEntityList.size());
            }else{
                //调用保存广告操作
             //   offerService.pull(offerEntityList,batchNo);
            }
            LOGGER.info("当前线程:"+Thread.currentThread().getName());
            LOGGER.info("沉睡5秒，等事物提交？？？？");
            Thread.sleep(5000);
            batchSetOffers.taskRun();
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            LOGGER.error("batchGetOffersByOfferslook ERROR - 错误代码:{},错误消息:{},错误Data:{}", resultModel.getCode(), resultModel.getMessage(), resultModel.getData());
            e.printStackTrace();
        }
        LOGGER.info("batchGetOffersByOfferslook end");
    }

    public int getRquestCount() throws RRException {

        String response = HttpUtils.doGet(apiDomain+getBatchesOffersURI+urlParams+"&offset=1&limit=1",usernamePasswordCredentials);
        LOGGER.info("response:{}",response);
        ResultModel resultModel = JSON.parseObject(response, ResultModel.class);
        if (resultModel.getCode() == 0) {
            GetOfferModel getOfferModel = JSON.parseObject(resultModel.getData(), GetOfferModel.class);
            LOGGER.info("offer 总数：{}", getOfferModel.getTotalRows());
            return getOfferModel.getTotalRows()/limit +1;
        } else {
            throw new RRException("获取总数异常");
        }
    }

    private void transfer(List<GetOfferModel.OfferAllBean> offerAllBeanList,List<OfferEntity> offerEntityList){
        for(GetOfferModel.OfferAllBean offerAllBean:offerAllBeanList){
            GetOfferModel.OfferAllBean.OfferBean offerBean = offerAllBean.getOffer();
            OfferEntity offerEntity = new OfferEntity();
            //TODO 可配置
            offerEntity.setDspChannelId(89);
            //TODO 可配置
            offerEntity.setSspChannelId(26);
            offerEntity.setDspOfferId(offerBean.getId());
            offerEntity.setName(offerBean.getName());
            offerEntity.setDescription(offerBean.getDescription());
            offerEntity.setStatus(offerBean.getStatus());
            offerEntity.setCategory(offerBean.getCategory());
            offerEntity.setOfferApproval(offerBean.getOffer_approval());
            offerEntity.setOfferApprovalMsg(offerBean.getOffer_approval_msg());
            offerEntity.setTrackingLink(offerBean.getTracking_link());
            //TODO 日期转换
            offerEntity.setEndDate(DateUtils.formatBySecs(offerBean.getEnd_date()));
            offerEntity.setPricingType(offerBean.getPricing_type());
            offerEntity.setPayout(offerBean.getPayout());
            offerEntity.setPercentPayout(offerBean.getPercent_payout());
            offerEntity.setCurrency(offerBean.getCurrency());
            offerEntity.setPreviewUrl(offerBean.getPreview_url());
            offerEntity.setConversionProtoco(offerBean.getConversion_protocol()+"");
            offerEntity.setConversionProtocolMsg(offerBean.getConversion_protocol_msg());
            offerEntity.setThumbnail(offerBean.getThumbnail());
            offerEntity.setOfferGeo(offerAllBean.getOffer_geo());
            offerEntity.setOfferVbt(offerAllBean.getOffer_vbt());
            offerEntity.setOfferEvent(offerAllBean.getOffer_event());
            offerEntity.setOfferPostback(offerAllBean.getOffer_postback());
            offerEntity.setOfferPlatform(offerAllBean.getOffer_platform());
            offerEntity.setOfferCreative(offerAllBean.getOffer_creative());
            offerEntity.setOfferCap(offerAllBean.getOffer_cap());
            //offerEntity.setCreateTime(new Date());
            offerEntity.setUpdateTime(new Date());
            offerEntity.setBatchNo(batchNo);
            offerEntity.setPushStatus("Active");
            offerEntityList.add(offerEntity);
        }
    }

}
